﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security;
using QCCure.Core;
using QCCure.Properties;

namespace QCCure
{
    public partial class FormSettings : Form
    {
        public QCController QC { get; set; }

        public FormSettings()
        {
            InitializeComponent();
        }

        private Settings Settings { get { return Properties.Settings.Default; } }

        private void FormSettings_Shown(object sender, EventArgs e)
        {
            textQCURL.Text = Settings.qcUrl;
            textUsername.Text = Settings.qcLoginName;

            if (Settings.qcPassword != null && Settings.qcPassword != "")
            {
                SecureString securePassword = SecureIt.DecryptString(Settings.qcPassword);
                textPassword.Text = SecureIt.ToInsecureString(securePassword);
            }
            else
            {
                textPassword.Text = "";
            }

            populateProject();
            checkAllowSavingDefects.Checked = Settings.allowSavingDefects;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (textQCURL.Text == "" || textUsername.Text == "" || textPassword.Text == "")
            {
                MessageBox.Show("Please enter QC URL and Username to retrieve the projects");
                return;
            }

            if (comboProject.SelectedItem == null)
            {
                MessageBox.Show("Please Select a valid project/domain");
                return;
            }

            Settings.qcUrl = textQCURL.Text;
            Settings.qcLoginName = textUsername.Text;
            
            if (textPassword.Text != "") {
                SecureString securePassword = SecureIt.ToSecureString(textPassword.Text);

                // clear the password from the textbox so it does not stay in an unsecure state any longer then necessary
                textPassword.Text = "";

                // if user has asked to save it, put it in the Settings file encrypted
                // save the password
                string encryptedPassword = SecureIt.EncryptString(securePassword);
                Settings.qcPassword = encryptedPassword;
            }
            else
            {
                // clear the password
                Settings.qcPassword = "";
            }

            QCProject project = comboProject.SelectedItem as QCProject;

            if (project != null)
            {
                Settings.qcDomain = project.Domain;
                Settings.qcProject = project.Project;
            }
            
            Settings.allowSavingDefects = checkAllowSavingDefects.Checked;

            Settings.Save();
            
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Hide();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {   
            // clear the password from the textbox so it does not stay in an unsecure state any longer then necessary
            textPassword.Text = "";

            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Hide();
        }

        private void buttonDownloadDomain_Click(object sender, EventArgs e)
        {
            try
            {
                if (textQCURL.Text == "" || textUsername.Text == "" || textPassword.Text == "")
                {
                    MessageBox.Show("Please enter QC URL, Username and Password to retrieve the projects");
                    return;
                }

                projects = null;
                comboProject.Text = "Loading projects";
                comboProject.Items.Clear();
                buttonDownloadDomain.Enabled = false;
                buttonSave.Enabled = false;
                backgroundWorkerGetProjects.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to retrive the projects due to: " + ex.Message);
                comboProject.Text = "Unable to load projects";
                buttonDownloadDomain.Enabled = true;
                buttonSave.Enabled = true;
            }
        }

        private void populateProject()
        {
            if (string.IsNullOrWhiteSpace(Settings.qcDomain) || string.IsNullOrWhiteSpace(Settings.qcProject))
            {
                return;
            }

            QCProject project = new QCProject(Settings.qcDomain, Settings.qcProject);
            if (comboProject.Items.Count == 0)
            {
                comboProject.Items.Add(project);
            }

            comboProject.SelectedItem = project;
        }

        private List<QCProject> projects;
        private void backgroundWorkerGetProjects_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                projects = QC.connectToQCAndGetProjectList(textQCURL.Text, textUsername.Text, textPassword.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to retrive the projects due to: " + ex.Message);
            }
        }

        private void backgroundWorkerGetProjects_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (projects != null)
                {
                    comboProject.Items.Clear();
                    comboProject.Items.AddRange(projects.ToArray());

                    populateProject();
                    comboProject.DroppedDown = true;
                }
            }
            catch (Exception ex)
            {
                comboProject.Text = "Unable to load projects";
                MessageBox.Show("Unable to retrive the projects due to: " + ex.Message);
            }
            finally
            {
                buttonDownloadDomain.Enabled = true;
                buttonSave.Enabled = true;
            }
        }

    }
}
